<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>DOM 的优化</title>
  </head>
  <body></body>

  <script>
    const bodyNode = document.getElementsByTagName('body')[0];
    const maxTime = 10000;

    console.time('before1');
    for (let i = 0; i < maxTime; i++) {
      const p = document.createElement('p');
      p.className = 'p_class_' + i;
      p.innerHTML = `this is p ---- ${i}`;
      bodyNode.appendChild(p);
    }
    console.timeEnd('before1');

    console.time('after1');
    const frag = document.createDocumentFragment();
    for (let i = 0; i < maxTime; i++) {
      const p = document.createElement('p');
      p.className = 'p_class_' + i;
      p.innerHTML = `this is p ---- ${i}`;
      frag.appendChild(p);
    }
    bodyNode.appendChild(frag);
    console.timeEnd('after1');

    console.time('after2');
    let stringFrag = '';
    const frag2 = document.createDocumentFragment();
    for (let i = 0; i < maxTime; i++) {
      stringFrag += `<p class="p_class_${i}">this is p ---- ${i}</p>`;
    }
    frag2.innerHTML = stringFrag;
    bodyNode.appendChild(frag2);
    console.timeEnd('after2');
  </script>
</html>
